#define  _CRT_SECURE_NO_WARNINGS 1
#include "list.h"

LTNode* BuyListNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	newnode->next = newnode->prev = NULL;
	newnode->data = x;
	return newnode;
}

LTNode* ListInit()
{
	LTNode* phead = BuyListNode(0);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}

void ListDestroy(LTNode* phead)
{
	assert(phead);

	LTNode* curr = phead->next;
	while (curr != phead)
	{
		LTNode* del = curr;
		curr = curr->next;
		free(del);
	}
	free(phead);
}

void ListPrint(LTNode* phead)
{
	printf("phead:");
	LTNode* curr = phead->next;
	while (curr != phead)
	{
		printf("%d ", curr->data);
		curr = curr->next;
	}
	printf("\n");
}

LTNode* ListFind(LTNode* phead, LTDataType x)
{
	LTNode* curr = phead->next;
	while (curr != phead)
	{
		if (curr->data == x)
			return curr;
		curr = curr->next;
	}
	return NULL;
}

void ListPushBack(LTNode* phead, LTDataType x)
{
	ListInsert(phead, x);
}

void ListPushFront(LTNode* phead, LTDataType x)
{
	ListInsert(phead->next, x);
}

void ListPopBack(LTNode* phead)
{
	ListErase(phead->prev);
}

void ListPopFront(LTNode* phead)
{
	ListErase(phead->next);
}

void ListInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* posPrev = pos->prev;
	LTNode* newnode = BuyListNode(x);

	posPrev->next = newnode;
	newnode->prev = posPrev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(LTNode* pos)
{
	assert(pos);
	assert(pos->next != pos);

	LTNode* posPrev = pos->prev;
	LTNode* posNext = pos->next;

	free(pos);
	posPrev->next = posNext;
	posNext->prev = posPrev;
}